package org.ade.monak.anak.util;

import java.util.List;

import org.ade.monak.anak.service.storage.DatabaseManagerAnak;
import org.ade.monak.anak.service.storage.LogMonakFileManager;

import android.content.Context;
import android.telephony.TelephonyManager;

public class IDGeneratorAnak {

	public IDGeneratorAnak(Context context, DatabaseManagerAnak databaseManager){
		if(databaseManager==null){
			mDatabaseManager = new DatabaseManagerAnak(context);
		}else{
			mDatabaseManager = databaseManager;
		}
		if(context!=null){
			mContext = context;			
		}
	}
	
	
	public String getIdMonitoring(){
		List<String> ids = mDatabaseManager.getIdMonitorings();
		String id = ID_MONITORING+generateAngkaId(ids);
		return id;
	}
	
	public String getIdLocation(){
		List<String> ids = mDatabaseManager.getIdLokasis();
		String id = ID_LOCATION+generateAngkaId(ids);
		return id;
	}
	
	public String getImei(){
		TelephonyManager telephonyManager = (TelephonyManager)
				mContext.getSystemService(Context.TELEPHONY_SERVICE);
		return telephonyManager.getDeviceId()+"A";
	}
	
	private String generateAngkaId(List<String> ids){
		int idAngka = 0;

		boolean ada = false;
		
		if(ids!=null && ids.size()>0){
			int i=0;
			for(String id:ids){
				
				if(id!=null&&!id.equals("")){
					idAngka = Integer.parseInt(id.substring(1));
				}else{
					idAngka = 0;	
				}
				
				if(idAngka==i){
					ada = true;
					i++;
				
				}else{
					ada = false;
					idAngka = i;
					break;
				}
				
			}
		}
	
		if(ada){
			idAngka++;	
		}
				
		String angka = ""+idAngka;
		int zeroLength = 9-angka.length();
		for(int i=zeroLength;i>0;i--){
			angka = "0"+angka;
		}

		return angka;
	}
	
	
	private static final char ID_MONITORING 	= 'M';
	private static final char ID_LOCATION		= 'L';
	
	private Context mContext;
	
	private DatabaseManagerAnak mDatabaseManager;
}
